﻿@model throneOfGames.Models.GameViewModel
<!-- King of Tokyo -->
<script>
    var randomImageArray = ["card1.png", "card2.png", "card3.png", "card4.png", "card5.png",
        "card6.png", "card7.png", "card8.png", "card9.png", "card10.png", ]


    var card0 = new Image()
    card0.src = "/Images/card1.png"
    var card1 = new Image()
    card1.src = "/Images/card2.png"
    var card2 = new Image()
    card2.src = "/Images/card3.png"
    var card3 = new Image()
    card3.src = "/Images/card4.png"
    var card4 = new Image()
    card4.src = "/Images/card5.png"
    var card5 = new Image()
    card5.src = "/Images/card6.png"
    var card6 = new Image()
    card6.src = "/Images/card7.png"
    var card7 = new Image()
    card7.src = "/Images/card8.png"
    var card8 = new Image()
    card8.src = "/Images/card9.png"
    var card9 = new Image()
    card9.src = "/Images/card10.png"


    function getRandomImage(imgArray, path) {

        path = path || 'Images/';
        var num = Math.floor(Math.random() * imgArray.length);
        var img = imgArray[num];
        var imgStr = '<img src="' + path + img + '" alt = "" width="80px" height="110px">';
        document.write(imgStr); document.close();
    }
    for (var i = 0; i < 3; i += 1) {
        getRandomImage(randomImageArray, '/images/')
    }
</script>

<!-- Images for the dice. -->
<div class="dieImages">
    <img src="/Images/kotstart.png" id="mydice0">
    <img src="/Images/kotstart.png" id="mydice1">
    <img src="/Images/kotstart.png" id="mydice2">
    <img src="/Images/kotstart.png" id="mydice3">
    <img src="/Images/kotstart.png" id="mydice4">
    <img src="/Images/kotstart.png" id="mydice5">
</div>
<!-- Checkboxes for the dice. -->
<div class="dieCheckboxes">
    <input type="checkbox" id="check0" />
    <input type="checkbox" id="check1" />
    <input type="checkbox" id="check2" />
    <input type="checkbox" id="check3" />
    <input type="checkbox" id="check4" />
    <input type="checkbox" id="check5" />
</div>

<!-- A button to throw the selected dice. -->
<form>
    <input type="button" id="throwDiceBtn" value="Throw dice!" />
</form>

<!-- A button to end the turn. -->
<form>
    <input type="button" value="End turn" id="calculateResults" />
</form>

<script>
    var counter = 1;
    //Initialise the starting stats
    @foreach(var m in Model.players)
            {
                <text>
                    $("#name" + counter).html('Player: ' + '@m.User.userName');
                    $("#points" + counter).html('Points: ' + '@m.playerPoints');
                    $("#energy" + counter).html('Energy: ' + '@m.playerEnergy');
                    $("#hp" + counter).html('Health: ' + '@m.playerHealth');
                    counter++;
                     
                </text>
            }
    //Remove extra players if the game has less then 4
    if (counter < 5) {
        for (counter; counter < 5; counter++) {
            document.getElementById('player'+counter).style.visibility = 'hidden';
        }
    }
    $(function () {
        // Preload the six images first.
        var face0 = new Image()
        face0.src = "/Images/kotOne.png"
        var face1 = new Image()
        face1.src = "/Images/kotTwo.png"
        var face2 = new Image()
        face2.src = "/Images/kotThree.png"
        var face3 = new Image()
        face3.src = "/Images/kotPaw.png"
        var face4 = new Image()
        face4.src = "/Images/kotEnergy.png"
        var face5 = new Image()
        face5.src = "/Images/kotHeart.png"
        
        // SignalR connection.
        var group = "@Model.game.ID";
        var hub = $.connection.gameHub;
        var obj = { "id": group };
        function checkGame()
        {
            if (score >= 20) {
                hub.server.declareWinner(("@Model.game.ID"), ("@Model.currPlayer.User.userName"), (" has won the game!!"));
                alert("You won!");
            }
            else {
                if (hpPoints > 0) {
                    hub.server.allDead(("@Model.game.ID")).done(function (result) {
                        if (result == true)
                        {
                            hub.server.declareWinner(("@Model.game.ID"), ("@Model.currPlayer.User.userName"), (" has won the game!!"));
                        }
                    });
                }
                else if (hpPoints <= 0)
                {
                    hub.server.playerDead(("@Model.game.ID"), ("@Model.currPlayer.User.userName"));
                    $.connection.stop();
                }
        }
    }
        function updatePlayers() {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "/Game/updatePlayerStatus",
                data: obj,
                dataType: "json",
                success: function (data) {
                    var counter = 1;
                    for (var i = 0; i < data.length; i++) {
                        $("#points" + (i + 1)).html('Points: ' + data[i].playerPoints);
                        $("#energy" + (i + 1)).html('Energy: ' + data[i].playerEnergy);
                        $("#hp" + (i + 1)).html('Health: ' + data[i].playerHealth);
                        if (data[i].isInside) {
                            $("#inTokyo" + (i + 1)).html("Currently in Tokyo");
                        }
                        else
                        {
                            $("#inTokyo" + (i + 1)).html(" ");
                        }
                    }
                },
                error: function (xhr, err) {
                    // Note: just for debugging purposes!
                    console.log("readyState: " + xhr.readyState +
                    "\nstatus: " + xhr.status);
                    console.log("responseText: " + xhr.responseText);
                }
            });
        }
        updatePlayers();
        setInterval(updatePlayers, 2000);
        // Point counters.
        var score = 0;

        // HP
        var hpPoints = 10;

        // Energy
        var energyPoints = 0;

        var turn = 'false';
        var turns = 0;
        var inside = 'false';
        // Array to hold the sides of the dice.
        var randomDice = new Array();
        
        hub.client.winnerDeclared = function (name, message) {
            alert(name + message);
        }
        hub.client.getAttack = function (name, player, attack, attacks) {
            if (attack == "tokyo")
            {
                if ('@User.Identity.Name' == player)
                {
                    hpPoints -= attacks;
                    $('#KotGameLog').append('<li><strong>' + name + '</strong> ' + ' attacks you for ' +
                        attacks + ' damage. ' + '</li>');
                    $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
                    hub.server.updatePlayer(("@Model.game.ID"), ("@Model.currPlayer.ID"), ("@Model.currPlayer.User.userName")
                    , (hpPoints), (energyPoints), (score));
                    if (hpPoints > 0) {
                        var y = confirm("Would you like to leave tokyo?");
                        if (y == true) {
                            hub.server.changeInside((group), (name), ("@Model.currPlayer.ID"));
                            checkGame();

                        }
                    }
                    else
                    {
                        hub.server.changeInside((group), (name), ("@Model.currPlayer.ID"));
                    }
                    checkGame();
                }
                else
                {
                    $('#KotGameLog').append('<li><strong>' + name + '</strong> ' + ' attacked ' + player + 'for ' +
                        attacks + ' damage. ' + '</li>');
                    $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
                    checkGame();
                }
            }
            else
            {
                hpPoints -= attacks;
                $('#KotGameLog').append('<li><strong>' + name + '</strong> ' + ' attacks everyone for ' +
                    attacks + ' damage. ' + '</li>');
                $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
                hub.server.updatePlayer(("@Model.game.ID"), ("@Model.currPlayer.ID"), ("@Model.currPlayer.User.userName")
                    , (hpPoints), (energyPoints), (score));
                checkGame();
            }
        }

        hub.client.playerUpdate = function (name, health, energy, points, attack) {
            $('#KotGameLog').append('<li><strong>' + name + '</strong> ' + 'got ' + health + ' health, ' +
                energy + ' energy, ' + points + ' points and ' + attack + ' attacks.' + '</li>');
            $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
        };

        hub.client.addNewMessageToPage = function (name, message) {
        // Add the message to the page. 
        $('#KotGameLog').append('<li><strong>' + name + '</strong> ' + message + '</li>');
        $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
        };
        // A function for throwing the dice.
    $.connection.hub.start().done(function () {
        hub.server.join(group);
        $("#throwDiceBtn").click(function ()
        {
            hub.server.isItMyTurn(group, "@User.Identity.Name").done(function (result) 
            {
                turn = result;
                if (turn == "true")
                {
                    for (var i = 0; i < 6; i++) {
                        document.getElementById("check" + i).disabled = false;
                    }
            document.getElementById("calculateResults").disabled = false;
            // We need this to see which die is selected.
            var heldDice = new Array(false, false, false, false, false, false);
            // We want to be able to print out the values to the log.
            var namesOfDice = new Array("One", "Two", "Three", "Paw", "Energy", "Heart");
            // Check if a die is selected and save that.
            for (var i = 0; i < 6; i++) {
                if (document.getElementById("check" + i).checked) {
                    heldDice[i] = true;
                }
                else {
                    heldDice[i] = false;
                }
            }

            // Create a random integer between 0 and 5.
            for (var i = 0; i < 6; i++) {
                if (heldDice[i] == false) {
                    randomDice[i] = Math.round(Math.random() * 5);
                    // Display the correct die based on the random number.
                    document.images["mydice" + i].src = eval("face" + randomDice[i] + ".src")
                    // Write out results to the gamelog.
                    hub.server.send((group), ("@User.Identity.Name"), (' threw a ' + namesOfDice[randomDice[i]] + '</li>'));
                    $('#KotGameLog').append('<li><strong>' + "@User.Identity.Name" + '</strong> ' + ' threw a ' + namesOfDice[randomDice[i]] + '</li>');
                    // Keep the scrollbar on the bottom.
                    $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
                }
                /*if (turns > 2) {
                    $("#throwDiceBtn").slideUp("slow");
                }*/
                }
               }
          });
      });
    
        $("#calculateResults").click(function () {
            for (var i = 0; i < 6; i++) {
                document.getElementById("check" + i).disabled = true;
            }
            document.getElementById("calculateResults").disabled = true;
                /* POINT CALCULATION */

                //Get current numbers for players stats before changing them

                //Counters
                var sendEnergy = 0;
                var sendHp = 0;
                var sendPoints = 0;
                var counter1 = 0;
                var counter2 = 0;
                var counter3 = 0;
                var attackCounter = 0;
                var energyCounter = 0;
                var totalScore = 0;
                var hpCounter = 0;
                for (var i = 0; i < 6; i++) {
                    switch (randomDice[i]) {
                        case 0:
                            counter1 += 1;
                            if (counter1 >= 3) {
                                totalScore += 1;
                                sendPoints += 1;
                            }
                            else if (counter1 > 3) {
                                totalScore += 1;
                                sendPoints += 1;
                            }
                            break;
                        case 1:
                            counter2 += 1;
                            if (counter2 == 3) {
                                totalScore += 2;
                                sendPoints += 2;
                            }
                            else if (counter2 > 3) {
                                totalScore += 1;
                                sendPoints += 1;
                            }
                            break;
                        case 2:
                            counter3 += 1;
                            if (counter3 == 3) {
                                totalScore += 3;
                                sendPoints += 3;
                            }
                            else if (counter3 > 3) {
                                totalScore += 1;
                                sendPoints += 1;
                            }
                            break;
                        case 3:
                            attackCounter += 1;
                            break;
                        case 4:
                            energyCounter += 1;
                            sendEnergy += 1;
                            energyPoints += energyCounter;
                            energyCounter = 0;
                            break;
                        case 5:
                            hpCounter += 1;
                            sendHp += 1;
                            if ((hpCounter + hpPoints) > 10) {
                                hpPoints = 10;
                            }
                            else {
                                hpPoints += hpCounter;
                            }
                            hpCounter = 0;
                            break;
                        default:
                            break;
                    }
                }
                turn = 'false';
                score += totalScore;
                $("#points" + "@Model.currPlayer.playerNumber").html("Points:" + score);
                $("#energy" + "@Model.currPlayer.playerNumber").html("Energy:" + energyPoints);
                $("#hp" + "@Model.currPlayer.playerNumber").html("Health:" + hpPoints);
                hub.server.updatePlayer(("@Model.game.ID"), ("@Model.currPlayer.ID"), ("@Model.currPlayer.User.userName")
                    , (hpPoints), (energyPoints), (score));
                hub.server.sendUpdatedPlayer(("@Model.game.ID"), ("@Model.currPlayer.User.userName"),
                    (sendHp), (sendEnergy), (sendPoints), (attackCounter))
                hub.server.updateTurn("@Model.game.ID");
                $('#KotGameLog').append('<li><strong>You</strong>' + ' got ' + sendHp + ' health, ' +
                    sendEnergy + ' energy ' + sendPoints + ' points and ' + attackCounter + ' attacks.' + '</li>');
                $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
                checkAttack(attackCounter);
                checkGame();
            });
        function checkAttack(attacks)
        {
            if (attacks > 0)
            {
                hub.server.attackTokyo(("@Model.game.ID"), ("@Model.currPlayer.User.userName"), ("@Model.currPlayer.ID"), (attacks));
                $('#KotGameLog').append('<li><strong>You</strong>' + ' attack for ' + attacks + ' damage.' + '</li>');
                $('#KotGameLog').stop().animate({ scrollTop: $("#KotGameLog")[0].scrollHeight }, 800);
            }
            checkGame();
            updatePlayers();
        }
    });
    });
</script>
